package Receivers

import "gitee.com/ling-bin/network/netInterface"

//SpliceStartFinishManyReceiver 开始结束分包器，多字节【jt808适用】
type SpliceStartFinishManyReceiver struct {
	startSymbol      []byte
	startSymbolsLen  int
	finishSymbol     []byte
	finishSymbolsLen int
}

// NewSpliceStartFinishManyReceiver 按照开始结束符来粘包
func NewSpliceStartFinishManyReceiver(startSymbol []byte, finishSymbol []byte) *SpliceStartFinishManyReceiver {
	return &SpliceStartFinishManyReceiver{
		startSymbol:      startSymbol,
		startSymbolsLen:  len(startSymbol),
		finishSymbol:     finishSymbol,
		finishSymbolsLen: len(finishSymbol),
	}
}

//GetHeadLen 包头必须要的长度
func (s *SpliceStartFinishManyReceiver) GetHeadLen() int {
	return s.startSymbolsLen + s.finishSymbolsLen
}

//CanHandle 是否能处理
func (s *SpliceStartFinishManyReceiver) CanHandle(conn netInterface.IConnection, buffer []byte) bool {
	isOk := true
	for  i := 0; i < s.startSymbolsLen; i++ {
		if s.startSymbol[i] != buffer[i] {
			isOk = false
		}
	}
	return isOk
}

//Reset 重置分包状态为初始状态
func (s *SpliceStartFinishManyReceiver) Reset()  {

}

//Receiver 分包处理
func (s *SpliceStartFinishManyReceiver) Receiver(conn netInterface.IConnection, buffer []byte) ([]byte, int) {
	var (
		bfLen      = len(buffer)
		startIndex = -1
		startOkLen = 0
		endOkLen   = 0
		isStart    = false
	)
	for i := 0; i < bfLen; i++ {
		if !isStart {
			if buffer[i] == s.startSymbol[startOkLen] {
				startOkLen++
				if startOkLen == s.startSymbolsLen {
					isStart = true
					startIndex = i
				}
			} else {
				isStart = false
			}
		} else {
			if buffer[i] == s.finishSymbol[endOkLen] {
				endOkLen++
				if endOkLen == s.finishSymbolsLen {
					hData := buffer[startIndex : i+1]
					startIndex = i + 1
					return hData, i + 1
				}
			}
		}
	}
	return nil, startIndex
}
